package com.lz.message.redis;

import java.util.Date;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;


/**
 * 讲zset中到期的消息移动到list中供消费者处理
 * @author luozhen
 *
 */
public class MessageCopy implements Runnable{

	private StringRedisTemplate redisTemplate;
	
	private String listKey;
	
	private String zsetKey;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(Consumer.class);
	
	public MessageCopy(StringRedisTemplate stringRedisTemplate,String listKey, String zsetKey) {
		this.listKey = listKey;
		this.zsetKey = zsetKey;
		this.redisTemplate = stringRedisTemplate;
	}
	
	public void run() {
		
		while(true) {
			// ZRANGEBYSCORE 取score小于等于当前时间的数据
	        Date date = new Date();
	        Set<String> list = redisTemplate.opsForZSet().rangeByScore(zsetKey, 0, date.getTime());
	        if (list == null || list.size() == 0) {
	            return;
	        }
	        try {
	            // 发送队列
	        	redisTemplate.opsForList().leftPushAll(listKey, list);
	            // ZREMRANGEBYSCORE() 删除score小于等于当前时间的数据
	            redisTemplate.opsForZSet().removeRangeByScore(zsetKey, 0, date.getTime());
	        } catch (Exception e) {
	            // TODO: handle exception
	        	LOGGER.error("队列发送失败", e);
	        }
		}
			
	}	
}
